/**
 * 
 */
let API, HOST

if (process.env.NODE_ENV === 'development') {
	HOST = 'http://localhost/gushi/public/'
} else {
	HOST = 'http://ym.ymob.top/'
}
API = HOST + 'index.php/'

const request = (options) => {
	let phone = uni.getStorageSync('phone') || ''
	let url = API + options.url
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			method: options.method || "GET",
			data: {
				phone,
				...(options.data || {})
			},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			sslVerify: false,
			success: (res) => {
				if (res.data.code === 401) {
					uni.showToast({
						title: '您已被迫下线，请重新登录！',
						icon: 'none'
					})
					uni.reLaunch({
						url: '/pages/login'
					})
				} else if (res.data.code === 500) {
					reject(res.data)
				} else {
					resolve(res.data.data)
				}
			},
			fail: (err) => {
				reject(err)
			},
		})
	})
}

export function RecordPath(path) {
	return HOST + path
}

/**
 * 登录
 */
export function LoginApi(data) {
	return request({
		method: 'post',
		url: 'api/index/login',
		data: data
	})
}

/**
 * 获取题目
 */
export function questionApi(data) {
	return request({
		method: 'get',
		url: 'api/index/question',
		data: data
	})
}

/**
 * 用户信息
 */
export function userinfoApi(data) {
	return request({
		method: 'get',
		url: 'api/index/userinfo',
		data: data
	})
}

/**
 * 回答问题
 */
export function anwserApi(filePath, data = {}) {
	let phone = uni.getStorageSync('phone') || ''
	let url = API + 'api/index/anwser'
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url,
			filePath: filePath,
			name: 'file',
			formData: {
				phone,
				...data
			},
			header: {
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			success: (res) => {
				if (typeof res.data == 'string') {
					res.data = JSON.parse(res.data)
				}
				resolve(res.data.data)
			},
			fail: (err) => {
				reject(err)
			}
		})
	})

}
